package com.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Luiz
 * 
 */
public class FileUtil {

	private static String SERVIDOR = "184.107.67.241";
	private static String USUARIO = "multmovi";
	private static String SENHA = "muL03@vi429";

	public void upload(String fileName, File source)
			throws MalformedURLException, IOException {
		if (SERVIDOR != null && fileName != null && source != null) {
			StringBuffer sb = new StringBuffer("ftp://");

			sb.append(USUARIO);
			sb.append(':');
			sb.append(SENHA);
			sb.append('@');

			sb.append(SERVIDOR);
			sb.append('/');
			sb.append(fileName);

			sb.append(";type=i");

			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				URL url = new URL(sb.toString());
				URLConnection urlc = url.openConnection();

				bos = new BufferedOutputStream(urlc.getOutputStream());
				bis = new BufferedInputStream(new FileInputStream(source));

				int i;
				// read byte by byte until end of stream
				while ((i = bis.read()) != -1) {
					bos.write(i);
				}
			} finally {
				if (bis != null)
					try {
						bis.close();
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
				if (bos != null)
					try {
						bos.close();
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
			}
		} else {
			System.out.println("Input not available.");
		}
	}

	public void download(String fileName, File destination)
			throws MalformedURLException, IOException {
		if (SERVIDOR != null && fileName != null && destination != null) {
			StringBuffer sb = new StringBuffer("ftp://");
			sb.append(USUARIO);
			sb.append(':');
			sb.append(SENHA);
			sb.append('@');

			sb.append(SERVIDOR);
			sb.append('/');
			sb.append(fileName);

			sb.append(";type=i");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				URL url = new URL(sb.toString());
				URLConnection urlc = url.openConnection();

				bis = new BufferedInputStream(urlc.getInputStream());
				bos = new BufferedOutputStream(new FileOutputStream(
						destination.getName()));

				int i;
				while ((i = bis.read()) != -1) {
					bos.write(i);
				}
			} finally {
				if (bis != null)
					try {
						bis.close();
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
				if (bos != null)
					try {
						bos.close();
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
			}
		} else {
			System.out.println("Input not available");
		}
	}
}
